package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.Region;
import com.ruoyi.mapper.RegionMapper;
import com.ruoyi.service.RegionService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 25088
* @description 针对表【region(地域表)】的数据库操作Service实现
* @createDate 2024-09-14 15:02:26
*/
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region>
    implements RegionService {

    //获取所有地区
    @Override
    public List<Region> getAllRegion() {
        //根据排序字段排序
        QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Region> num = regionQueryWrapper.orderByAsc("num");
        List<Region> list = this.list(num);
        List<Region> regions = regions(0, list);
        return regions;
    }

    public List<Region> regions(Integer id,List<Region> list) {
        //帅选父级id
        List<Region> collect = list.stream().filter(item -> item.getSuperclassId().equals(id)).collect(Collectors.toList());
        //递归设置自己的字级
        List<Region> collect1 = collect.stream().map(item -> {
            List<Region> regions = regions(item.getId(), list);
            //防止多一级 校验非空
            if (regions.size() > 0) {
                item.setChildren(regions);
            }
            return item;
        }).collect(Collectors.toList());
        return collect1;

    }
}




